package com.lemon.stock.viewmodel

import androidx.compose.runtime.getValue
import androidx.compose.runtime.mutableStateOf
import androidx.compose.runtime.setValue
import androidx.lifecycle.ViewModel
import androidx.lifecycle.viewModelScope
import androidx.navigation.NavHostController
import com.lemon.stock.net.ApiHttp
import com.lemon.stock.net.apiCall
import com.lemon.stock.util.AuthManager
import com.lemon.stock.widget.Toaster
import kotlinx.coroutines.launch

class LoginViewModel: ViewModel() {
    var username by mutableStateOf("")
    var password by mutableStateOf("")

    fun login(navController: NavHostController) {
        viewModelScope.launch {
            if( username.isEmpty()){
                Toaster.show("请输入用户名")
                return@launch
            }
            if(password.isEmpty()){
                Toaster.show("请输入密码")
                return@launch
            }

            val loginRes = apiCall { ApiHttp.get().login(username, password) }

            if(loginRes.isSuccess()){
                AuthManager.onLogin(loginRes.data!!)
                navController.popBackStack()
                Toaster.show("登录成功")
            }else{
                Toaster.show(loginRes.msg)
            }
        }
    }
}